<template>
    <div id="department">
        <!-- 卡片视图区域 -->
        <el-card>
            <el-row :gutter="20">
                <el-col :span="8">
                    <!-- 搜索与添加区域 -->
                    <el-input placeholder="请输入学院名称或ID"
                        v-model="queryInfo.query"
                        clearable>
                        <template #append>
                            <el-button @click="handleSearch">
                                <el-icon>
                                    <search />
                                </el-icon>
                            </el-button>
                        </template>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary"
                        @click="addDialogVisible = true">添加学院</el-button>
                </el-col>
            </el-row>
            <!-- 学院列表区域 -->
            <el-table :data="departmentList"
                :row-class-name="getRowClass"
                border
                stripe>
                <el-table-column type="index"></el-table-column>
                <el-table-column label="学院ID"
                    prop="departmentId"></el-table-column>
                <el-table-column label="学院名称"
                    prop="departmentName"
                    width="190px"></el-table-column>
                <el-table-column label="学院描述"
                    prop="departmentDescription"></el-table-column>
                <el-table-column label="操作"
                    width="200px">
                    <template v-slot="scope">
                        <!-- 修改按钮 -->
                        <el-button type="primary"
                            @click="showEditDialog(scope.row.departmentId)">
                            <el-icon>
                                <edit />
                            </el-icon>
                        </el-button>
                        <!-- 删除按钮 -->
                        <el-button type="danger"
                            @click="handleDelete(scope.row.departmentId)">
                            <el-icon>
                                <delete />
                            </el-icon>
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页区域 -->
            <el-pagination v-model:current-page="queryInfo.pagenum"
                v-model:page-size="queryInfo.pagesize"
                :total="total"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </el-card>

        <!-- 添加学院对话框 -->
        <el-dialog v-model="addDialogVisible"
            title="添加学院"
            width="50%">
            <el-form :model="addForm"
                :rules="addFormRules"
                ref="addFormRef"
                label-width="80px">
                <el-form-item label="学院ID"
                    prop="departmentId">
                    <el-input v-model="addForm.departmentId"
                        autocomplete="off" />
                </el-form-item>
                <el-form-item label="学院名称"
                    prop="departmentName">
                    <el-input v-model="addForm.departmentName"
                        autocomplete="off" />
                </el-form-item>
                <el-form-item label="学院描述"
                    prop="departmentDescription">
                    <el-input v-model="addForm.departmentDescription"
                        autocomplete="off" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="addDialogVisible = false">取消</el-button>
                <el-button type="primary"
                    @click="submitAddForm">确定</el-button>
            </template>
        </el-dialog>

        <!-- 修改学院对话框 -->
        <el-dialog v-model="editDialogVisible"
            title="修改学院信息"
            width="50%">
            <el-form :model="editForm"
                ref="editFormRef"
                label-width="80px">
                <el-form-item label="学院ID">
                    <el-input v-model="editForm.departmentId"
                        disabled /> <!-- 不可修改 -->
                </el-form-item>
                <el-form-item label="学院名称"
                    prop="departmentName">
                    <el-input v-model="editForm.departmentName" />
                </el-form-item>
                <el-form-item label="学院描述"
                    prop="departmentDescription">
                    <el-input v-model="editForm.departmentDescription" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="editDialogVisible = false">取消</el-button>
                <el-button type="primary"
                    @click="submitEditForm">保存修改</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<style scoped>
/* 自定义删除动画样式 */
.deleting-row {
    animation: fadeOut 0.5s ease-in-out;
}

@keyframes fadeOut {
    from {
        opacity: 1;
        transform: translateX(0);
    }
    to {
        opacity: 0;
        transform: translateX(20px);
    }
}
</style>

<script>
import {
    getDepartmentList,
    addDepartment,
    updateDepartment,
    deleteDepartment,
    getDepartmentDetail
} from '@/api/department';

export default {
    data() {
        return {
            // 查询参数
            queryInfo: {
                pagenum: 1,       // 当前页码
                pagesize: 10,     // 每页显示数量
                query: '',        // 查询关键词
                orderBy: 0        // 排序方式(后端默认0)
            },
            // 学院列表数据
            departmentList: [],
            // 总数据条数
            total: 0,
            // 控制对话框显示与隐藏
            addDialogVisible: false,
            editDialogVisible: false,
            // 正在删除的ID列表（用于动画）
            deletingIds: [],
            // 添加学院表单数据
            addForm: {
                departmentId: "",
                departmentName: "",
                departmentDescription: ""
            },
            // 添加表单验证规则
            addFormRules: {
                departmentId: [{ required: true, message: "请输入学院ID", trigger: "blur" }],
                departmentName: [{ required: true, message: "请输入学院名称", trigger: "blur" }],
                departmentDescription: [{ required: true, message: "请输入学院描述", trigger: "blur" }]
            },
            // 编辑学院表单数据
            editForm: {
                departmentId: "",
                departmentName: "",
                departmentDescription: ""
            },
            // 编辑表单验证规则
            editFormRules: {
                departmentName: [{ required: true, message: "请输入学院名称", trigger: "blur" }],
                departmentDescription: [{ required: true, message: "请输入学院描述", trigger: "blur" }]
            }
        };
    },
    created() {
        this.fetchDepartmentList();
    },
    methods: {
        // 获取学院列表
        async fetchDepartmentList() {
            console.log("进入学院列表获取方法");
            
            try {
                // 构建请求体参数（与后端Department实体字段匹配）
                const requestBody = {
                    departmentName: this.queryInfo.query // 按学院名称搜索
                };

                // 调用API（路径参数+请求体）
                const res = await getDepartmentList(
                    this.queryInfo.pagenum,
                    this.queryInfo.pagesize,
                    this.queryInfo.orderBy,
                    requestBody
                );

                // 处理响应数据
                if (res.code === 200) {
                    this.departmentList = res.data.list || [];
                    console.log('学院数据:', this.departmentList);
                    this.total = res.data.total || 0;
                } else {
                    this.$message.error(res.message || '获取学院列表失败');
                }
            } catch (error) {
                console.error('获取学院列表失败:', error);
                this.$message.error('获取学院列表失败，请稍后再试');
            }
        },

        // 处理搜索
        handleSearch() {
            this.queryInfo.pagenum = 1; // 重置页码
            this.fetchDepartmentList();
        },

        // 处理分页大小变化
        handleSizeChange(newSize) {
            this.queryInfo.pagesize = newSize;
            this.fetchDepartmentList();
        },

        // 处理页码变化
        handleCurrentChange(newPage) {
            this.queryInfo.pagenum = newPage;
            this.fetchDepartmentList();
        },

        // 显示编辑对话框
        async showEditDialog(departmentId) {
            try {
                // 获取学院详情
                const res = await getDepartmentDetail(departmentId);
                if (res.code === 200) {
                    this.editForm = res.data;
                    this.editDialogVisible = true;
                } else {
                    this.$message.error(res.message || '获取学院详情失败');
                }
            } catch (error) {
                console.error('获取学院详情失败:', error);
                this.$message.error('获取学院详情失败，请稍后再试');
            }
        },

        // 提交添加表单
        async submitAddForm() {
            this.$refs.addFormRef.validate(async (valid) => {
                if (valid) {
                    try {
                        const res = await addDepartment(this.addForm);
                        if (res.code === 200) {
                            this.$message.success('添加学院成功');
                            this.addDialogVisible = false;
                            this.fetchDepartmentList();
                            // 重置表单
                            this.$nextTick(() => {
                                this.$refs.addFormRef.resetFields();
                            });
                        } else {
                            this.$message.error(res.message || '添加学院失败');
                        }
                    } catch (error) {
                        console.error('添加学院失败:', error);
                        this.$message.error('添加学院失败，请稍后再试');
                    }
                }
            });
        },

        // 提交编辑表单
        async submitEditForm() {
            this.$refs.editFormRef.validate(async (valid) => {
                if (valid) {
                    try {
                        const res = await updateDepartment(this.editForm);
                        if (res.code === 200) {
                            this.$message.success('修改学院成功');
                            this.editDialogVisible = false;
                            this.fetchDepartmentList();
                        } else {
                            this.$message.error(res.message || '修改学院失败');
                        }
                    } catch (error) {
                        console.error('修改学院失败:', error);
                        this.$message.error('修改学院失败，请稍后再试');
                    }
                }
            });
        },

        // 处理删除
        async handleDelete(departmentId) {
            try {
                // 添加删除动画标记
                this.deletingIds.push(departmentId);

                // 确认删除
                await this.$confirm(
                    '确认删除该学院? 此操作不可恢复',
                    '提示',
                    {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                );

                // 调用删除API
                const res = await deleteDepartment(departmentId);
                if (res.code === 200) {
                    this.$message.success('删除学院成功');
                    this.fetchDepartmentList();
                } else {
                    this.$message.error(res.message || '删除学院失败');
                }
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('删除学院失败:', error);
                    this.$message.error('删除学院失败，请稍后再试');
                }
            } finally {
                // 移除动画标记
                this.deletingIds = this.deletingIds.filter(id => id !== departmentId);
            }
        },

        // 获取删除行样式
        getRowClass({ row }) {
            return this.deletingIds.includes(row.departmentId) ? 'deleting-row' : '';
        }
    },
    // 对话框打开时刷新数据
    watch: {
        addDialogVisible(newVal) {
            if (newVal) {
                // 重置表单数据
                this.addForm = {
                    departmentId: "",
                    departmentName: "",
                    departmentDescription: ""
                };
            }
        }
    }
};
</script>